<template>
  <div class="app-container">
    <el-card class="mar_bottom">
      <el-search-form label-width="90px" @search="onSearch" @reset="onReset">
        <el-form-item>
          <el-select
            size="small"
            style="width: 100px; margin-right: -2px"
            v-model="timeType"
            placeholder="请选择"
          >
            <el-option label="创建时间" value="createDate"></el-option>
            <el-option label="订单时间" value="orderTime"></el-option>
          </el-select>
          <el-date-picker
            size="small"
            v-model="searchBody.timeRange"
            style="width: 350px"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="城市">
          <el-cascader
            v-model="codeList"
            size="small"
            :options="regionTree"
            :props="{
              label: 'name',
              value: 'code',
              checkStrictly: true,
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="公司">
          <el-select
            size="small"
            v-model="searchBody.companyId"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.companyName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商务手机号">
          <el-input
            clearable
            size="small"
            v-model="searchBody.pUserPhone"
            class="el-input__small"
          ></el-input>
        </el-form-item>
      </el-search-form>
      <el-button type="primary" size="small" @click="handleClick('exportOut')"
        >导出数据</el-button
      >
    </el-card>

    <el-card>
      <div>订单总金额 : {{ totalOrderPrice }}</div>
      <el-tabs
        style="margin-top: 15px"
        v-model="searchBody.xiansuoStatus"
        @tab-click="getData"
      >
        <el-tab-pane label="全部" name="0"></el-tab-pane>
        <el-tab-pane label="新线索" name="1"></el-tab-pane>
        <el-tab-pane label="无效" name="2"></el-tab-pane>
        <el-tab-pane label="已量房" name="3"></el-tab-pane>
        <el-tab-pane label="重复订单" name="4"></el-tab-pane>
        <el-tab-pane label="已签单" name="5"></el-tab-pane>
        <el-tab-pane label="未接通" name="6"></el-tab-pane>
        <el-tab-pane label="申请退款" name="7"></el-tab-pane>
        <el-tab-pane label="退款成功" name="8"></el-tab-pane>
      </el-tabs>
      <!--      <div class="flex-vc just_betwwen mar_bottom">

        <div>
          <el-button
            title="刷新"
            icon="el-icon-refresh-right"
            size="medium"
            circle
            @click="getData"
          ></el-button>
          <el-dropdown :hide-on-click="false" trigger="click">
            <el-button
              style="margin-left: 10px"
              title="筛选列"
              icon="el-icon-menu"
              size="medium"
              circle
            ></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item, idx) in tableColumn" :key="idx">
                <el-checkbox v-model="item.checked">{{
                  item.label
                }}</el-checkbox>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>-->
      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeOpts"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
      <div class="mt20">
        <el-table
          border
          v-loading="loading.list"
          :data="list"
          ref="multipleTable"
        >
          <el-table-column
            label="订单时间"
            prop="createDate"
            align="center"
            width="160"
          ></el-table-column>
          <el-table-column
            label="订单号"
            prop="orderNo"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            label="公司名称"
            prop="companyName"
            align="center"
            width="200"
          ></el-table-column>
          <el-table-column
            label="线索ID"
            prop="orderId"
            align="center"
            width="100"
          >
            <template slot-scope="scope">
              <el-tag
                disable-transitions>{{scope.row.orderId}}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="订单手机号"
            prop="orderPhone"
            align="center"
            width="100"
          ></el-table-column>
          <el-table-column
            label="订单城市"
            prop="orderCityValue"
            align="center"
            width="150"
          ></el-table-column>
          <el-table-column
            label="订单地址"
            prop="orderAddress"
            align="center"
            width="200"
          ></el-table-column>

          <el-table-column
            label="订单价格"
            prop="orderPrice"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            label="订单价格"
            prop="orderPrice"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            label="状态"
            prop="xiansuoStatusValue"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            label="申请退款时间"
            prop="refundApplyDate"
            align="center"
            width="100">
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="160"
            fixed="right"
          >
            <template slot-scope="scope">
              <div>

                <el-button
                  type="text"
                  size="mini"
                  @click="handleClick('liangfang', scope.row)"
                  >详情</el-button
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        small
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="pageSizeOpts"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import {
  paidanOrder,
  selectPaidanPageVo,
  selectRegionTree,
  sysDictbyMultiType,
  addNewOrder,
  editXiansuo,
  exportInData,
  exportOutData,
  exportSysRegion,
  selectJiaZhuangOrderPage,
  jiazhuangdingdanshenhe,
  selectTotalOrderPrice,
  exportJiazhuangOrderList,
  houtaiSetLiangfang,
  selectZxOrderPageData,
  selectCompanyVoList,
} from "@/api/api.js";
import { sysDict_delete } from "@/api/dataDict";
import { downloadFile } from "@/utils/index";

const getDefaultForm = () => ({
  name: null,
  sex: null,
  phone: null,
  addrCode: null,
  address: null,
  mianji: null,
  resouces: null,
  remark: null,
  logs: null,
  marketingType: null,
});
const getDefaultSearchBody = () => ({
  timeRange: null,
  resource: null,
  phone: null,
  yezhu: null,
  orderNo: null,
  userIdList: null,
  id: null,
  audiStatus: "0",
  audiDate: null,
  isLiangfang: null,
  pUserPhone: null,
  userPhone: null,
  companyId: null,
  xiansuoStatus:"0",
});
export default {
  data() {
    return {
      companyList: [],
      regionIdList:null,
      codeList: null,
      regionTree: [],
      shenheLoading: false,
      orderRiZhi: [],
      areaOptions: [],
      qdzOptions: [],
      resourceOptions: [],
      fw1Options: [],
      fw2Options: [],
      zxfs1Options: [],
      zxfs2Options: [],
      zxfs3Options: [],
      zxfs4Options: [],
      xhfgOptions: [],
      zxysOptions: [],
      jsStatusOptions: [],
      timeType: "createDate",
      searchType: "phone",
      dialogTitle: "",
      dialogTitle2: "",
      dialogTitle3: "",
      handleType: "",
      pageNo: 1,
      pageSize: 20,
      totalCount: 0,
      pageSizeOpts: [20, 50, 100, 300, 500],
      loading: {
        list: false,
        list2: false,
      },
      list: [],
      paidanData: {},
      selectRow: [], // 选中行
      lookDialog: false,
      editDialog: false,
      paidanDialog: false,
      updateForm: getDefaultForm(),
      searchBody: getDefaultSearchBody(),
      totalOrderPrice: 0,
      tableColumn: [
        {
          label: "线索ID",
          checked: true,
        },
        {
          label: "线索业主",
          checked: true,
        },
        {
          label: "线索手机",
          checked: true,
        },
        {
          label: "线索城市",
          checked: true,
        },
        {
          label: "派单",
          checked: true,
        },
        {
          label: "接单",
          checked: true,
        },
        {
          label: "订单",
          checked: true,
        },
        {
          label: "结算",
          checked: true,
        },
        {
          label: "标记",
          checked: true,
        },
        {
          label: "更新小计",
          checked: true,
        },
        {
          label: "来源",
          checked: true,
        },
        /* {
          label: "管理员/渠道主/达人",
          checked: true,
        },*/
        /*{
          label: "手机归属",
          checked: true,
        },
        {
          label: "线索时间",
          checked: true,
        },
        {
          label: "需求时间（订单）",
          checked: true,
        },
        {
          label: "更新时间",
          checked: true,
        },
        {
          label: "更新人",
          checked: true,
        },*/
      ],
      tableColumn2: [
        {
          label: "线索ID",
          checked: true,
        },
        {
          label: "订单GUID",
          checked: false,
        },
        {
          label: "线索UUID",
          checked: true,
        },
        {
          label: "线索姓名",
          checked: true,
        },
        {
          label: "线索城市",
          checked: true,
        },
        {
          label: "线索时间",
          checked: true,
        },
        {
          label: "渠道主",
          checked: true,
        },
        {
          label: "达人",
          checked: true,
        },
        {
          label: "派单时间",
          checked: true,
        },
        {
          label: "接单时间",
          checked: true,
        },
        {
          label: "产生需求",
          checked: true,
        },
        {
          label: "需求时间(订单)",
          checked: true,
        },
        {
          label: "需求城市",
          checked: true,
        },
        {
          label: "渠道主奖励",
          checked: true,
        },
        {
          label: "达人奖励",
          checked: true,
        },
        {
          label: "结算状态",
          checked: true,
        },
        {
          label: "结算时间",
          checked: true,
        },
      ],
    };
  },
  created() {
    this.getData();
    //this.getQdzOptions();
    //this.getOptions();
  },
  methods: {
    doLayout() {
      this.$nextTick(() => {
        that.$refs.multipleTable.doLayout();
      });
    },
    handleChangeAudiDate() {
      // 假设我们要转换到东八区（北京时间）
      const timezoneOffset = new Date().getTimezoneOffset();
      const offset = 8 * 60 - timezoneOffset; // 东八区比UTC偏前8小时
      const date = new Date(
        this.searchBody.audiDate.getTime() + offset * 60000
      );
      this.searchBody.audiDate = date;
      // 现在 date 是东八区的时间
      console.log("东八区时间:", date);
    },
    onSearchTypeChange(key) {
      let val;
      for (let key2 of ["yezhu", "phone", "orderNo", "id"]) {
        val = this.searchBody[key2] || val;
      }
      this.searchBody = Object.assign(this.searchBody, {
        [key]: val,
      });
    },
    getData() {
      this.loading.list = true;
      const { timeRange, userIdList, ...rest } = this.searchBody;
      const [startTime, endTime] = timeRange || [null, null];
      /*const _userIdList = (userIdList || []).reduce((a, b) => {
        return Array.from(new Set(a.concat(b)));
      }, []);*/

      var code = null;
      if (this.codeList != null) {
        var length = this.codeList.length;
        code = this.codeList[length - 1];
      }
      selectZxOrderPageData({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        startTime: startTime,
        endTime: endTime,
        code: code,

        ...rest,
      }).then(({ result }) => {
        this.list = result.data;
        this.totalCount = result.totalCount;
        this.loading.list = false;
      });
      selectRegionTree().then(({ result }) => {
        this.regionTree = result || [];
      });
      selectCompanyVoList().then(({ result }) => {
        this.companyList = result || [];
      });
      /*selectTotalOrderPrice({

        startTime: startTime,
        endTime: endTime,

        ...rest,
      }).then(({ result }) => {
        this.totalOrderPrice = result.orderPrice;
      });*/
    },
    getData2() {},
    handleSizeChange(val) {
      this.pageSize = val;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pageNo = val;
      this.getData();
    },
    handleSelectionChange(val) {
      this.selectIds = val.map((d) => d.id);
    },
    onSearch() {
      this.pageNo = 1;
      this.getData();
    },
    onReset() {
      this.pageNo = 1;
      this.searchBody = getDefaultSearchBody();
      this.getData();
    },
    handleClick(type, row, title) {
      this.handleType = type;
      switch (type) {
        case "liangfang":
         /* this.$confirm(`确认已量房？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            houtaiSetLiangfang({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
            });
          });*/
          break;
        case "look":
          this.dialogTitle = "订单ID:" + row.id + "-" + title;
          this.lookDialog = true;
          break;
        case "add":
          this.dialogTitle2 = "营销-添加";
          this.editDialog = true;
          this.updateForm = getDefaultForm();
          break;
        case "update":
          this.dialogTitle2 = "营销ID:" + row.id + "-编辑";
          selectXiansuoInfoVo({
            id: row.id,
          }).then((res) => {
            const { provinceCode, cityCode, areaCode, ...rest } = res.result;
            this.updateForm = Object.assign(rest, {
              addrCode: [provinceCode, cityCode, areaCode],
            });
            this.editDialog = true;
          });
          break;
        case "fenpai":
          break;
        case "exportOut":
          const { timeRange, userIdList, ...rest } = this.searchBody;
          const [startTime, endTime] = timeRange || [null, null];
          exportJiazhuangOrderList({
            startTime: startTime,
            endTime: endTime,
            phone: this.searchBody.phone,
            audiDateStr: this.searchBody.audiDate,
            audiStatus: this.searchBody.audiStatus,
          }).then((res) => {
            let fileName = res.headers["content-disposition"].replaceAll(
              /.*?filename=(.*?)/g,
              "$1"
            );
            downloadFile(res.data, decodeURI(fileName), "blob");
            this.$message.success("导出成功");
          });
          break;
        case "paidan":
          this.dialogTitle3 = "订单ID:" + row.id + "-派单";
          selectPaidanPageVo({
            id: row.id,
          }).then((res) => {
            const paidanData = res.result || {};
            paidanData.orderId = row.id;
            this.paidanData = paidanData;
            this.paidanDialog = true;
          });
          break;
        case "shenhe":
          this.shenheLoading = true;

          this.$confirm(`确认审核通过？`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            jiazhuangdingdanshenhe({
              id: row.id,
            }).then((res) => {
              this.$message.success(res.msg || "操作成功");
              this.getData();
              this.shenheLoading = false;
            });
          });
          break;
        default:
          return;
      }
    },
    handleSure(type) {
      type = type || this.handleType;
      const { addrCode, ...rest } = this.updateForm;
      const [provinceCode, cityCode, areaCode] = addrCode;
      switch (type) {
        case "add":
          addNewOrder({
            provinceCode,
            cityCode,
            areaCode,
            ...rest,
          }).then((res) => {
            this.$message.success("保存成功");
          });
          break;
        case "update":
          editXiansuo({
            provinceCode,
            cityCode,
            areaCode,
            ...rest,
          }).then((res) => {
            this.$message.success("保存成功");
          });
          break;
        case "paidan":
          paidanOrder({
            orderId: this.paidanData.orderId,
            jiazhuangPlatformIdList: this.selectRow.map((d) => {
              return d.jiazhuangPlatformId;
            }),
          }).then((res) => {
            this.$message.success("派单成功");
            this.paidanDialog = false;
          });
          break;
        default:
          return;
      }
    },
    onSelectionChange(val) {
      this.selectRow = val;
    },
    handleCommand(command) {
      this.$message("click on item " + command);
    },
    uploadData(params) {
      const form = new FormData();
      form.append("file", params.file);
      const loading = this.$loading({
        lock: true,
        text: "正在导入...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      exportInData(form)
        .then((res) => {
          this.$message.success("导入成功");
          loading.close();
        })
        .catch(() => {
          loading.close();
        });
    },
    beforeUpload(file) {
      if (file.size > 1 * 1024 * 1024) {
        this.$message.warning("上传的文件大小不能超过1MB!");
        return false;
      }
    },
  },
};
</script>

<style scoped>
.test1 {
  border: 1px solid red;
}
.mt20 {
  margin-top: 20px;
}

.el-table__row {
  border: 3px solid red !important;
}
</style>
